<template>
  <div class="bg_view">
    <tab :line-width="3.5" custom-bar-width="30px" active-color="#131A2A" bar-active-color="#448EFF"
         default-color="#9CA6BA">

      <tab-item @on-item-click="tabItemClick" :selected="tabItemShow == '0'">待支付</tab-item>
      <tab-item @on-item-click="tabItemClick" :selected="tabItemShow == '1'">已支付</tab-item>

    </tab>
    <div class="billBox">
      <!-- <div class="bill_box">
        <div class="bill_box_1">
          <div style="font-weight: bold;">门诊号： </div>


          <img src="@/assets/img/yizhifu.png" alt="" class="bill_box_1_status">

        </div>
        <div class="bill_box_2">
          <div class="left">
            <div>科室：</div>
            <div>医生：</div>
            <div style="font-size: 0.875rem">
              金额：<span style="color: #f72d23">￥</span>
            </div>
            <div>费用类别：</div>

            <div class="gery">开立时间：</div>
          </div>

        </div>
      </div> -->

      <template v-if="tabItemShow == 0">
        <template v-if="info.pactCode != '01'">
          <div class="noresult">
            <img src="@/assets/img/img_no results@2x.png" alt=""/>
            <div>医保挂号患者请前往窗口进行缴费</div>
          </div>

        </template>
        <template v-else>
          <template v-if="unpayList.length > 0">
            <div class="bill_box" @click="godetail(item)" v-for="item in unpayList">
              <div class="bill_box_img">
                查看详情<img src="@/assets/img/right.png" alt="">
              </div>

              <div class="bill_box_1">
                <div style="font-weight: bold;">门诊号：{{ payInfo.cardNo }}</div>
                <!-- <div style="color: #a4adbe" v-if="item.orderStatus == '1'">
                  已支付
                </div>
                <div style="color: #a4adbe" v-if="item.orderStatus == '2'">
                  已退款
                </div>
                <div style="color: red" v-if="item.orderStatus == '0'">待支付</div> -->
                <img src="@/assets/img/yizhifu.png" alt="" class="bill_box_1_status" v-if="item.orderStatus == '1'">
                <img src="@/assets/img/daizhifu.png" alt="" class="bill_box_1_status" v-if="item.orderStatus == '0'">
              </div>
              <div class="bill_box_2">
                <div class="left">
                  <div>科室：{{ item.deptName }}</div>
                  <div>医生：{{ item.doctorName }}</div>
                  <div style="font-size: 0.875rem">
                    金额：<span style="color: #f72d23">￥{{ item.payAmout | changAmout }}</span>
                  </div>
                  <div>费用类别：{{ item.feeName }}</div>

                  <div class="gery">开立时间：{{ item.receiptDate }}</div>
                </div>
                <!-- <div class="paybtn"  v-if="item.orderStatus == '0'" @click.stop="goPay(item.orderId)">支付</div> -->
              </div>
            </div>
          </template>
          <div class="noresult" v-else>
            <img src="@/assets/img/img_no results@2x.png" alt=""/>
            <div>暂无待支付费用</div>
          </div>

        </template>

      </template>
      <template v-if="this.tabItemShow == 1">
        <template v-if="payList.length > 0">
          <div class="bill_box" @click="godetail(item)" v-for="item in payList">
            <!-- <img src="@/assets/img/right.png" alt="" class="bill_box_img"> -->
            <div class="bill_box_img">
              查看详情<img src="@/assets/img/right.png" alt="">
            </div>
            <div class="bill_box_1">
              <div style="font-weight: bold;">门诊号：{{ payInfo.cardNo }}</div>
              <!-- <div style="color: #a4adbe" v-if="item.orderStatus == '1'">
                已支付
              </div>
              <div style="color: #a4adbe" v-if="item.orderStatus == '2'">
                已退款
              </div>
              <div style="color: red" v-if="item.orderStatus == '0'">待支付</div> -->
              <img src="@/assets/img/daizhifu.png" alt="" class="bill_box_1_status" v-if="item.orderStatus == '0'">
              <img src="@/assets/img/yizhifu.png" alt="" class="bill_box_1_status" v-if="item.orderStatus == '1'">
              <img src="@/assets/img/yituifei.png" alt="" class="bill_box_1_status" v-if="item.orderStatus == '2'">

            </div>
            <div class="bill_box_2">
              <div class="left">
                <div>发票ID：{{ item.hospSequence }}</div>
                <div>科室：{{ item.deptName }}</div>
                <div>医生：{{ item.doctorName }}</div>
                <div style="font-size: 0.875rem">
                  金额：<span style="color: #f72d23">￥{{ item.payAmout | changAmout }}</span>
                </div>
                <div>缴费类别：{{ item.feeName }}</div>

                <div class="gery" v-if="item.orderStatus == '2'">退费时间：{{ item.refundDate }}</div>
                <div class="gery" v-if="item.orderStatus == '1'">缴费时间：{{ item.payDate }}</div>
              </div>
              <!-- <div class="paybtn"  v-if="item.orderStatus == '0'" @click.stop="goPay(item.orderId)">支付</div> -->
            </div>
          </div>
        </template>


        <!-- <div class="nodate" >
          暂无已支付费用
        </div> -->
        <div class="noresult" v-else>
          <img src="@/assets/img/img_no results@2x.png" alt=""/>
          <div>暂无已支付费用</div>
        </div>
      </template>

      <div style="height: 3.75rem"></div>
    </div>
    <div class="payBottom" v-if="payInfo.unPay != 0">
      <div class="payBottom_1">
        &#x3000; 合计：<span>￥{{ payInfo.totalAmount | changAmout }}</span>
      </div>
      <div class="payBottom_2" @click="goPay(payInfo.orderId)">立即支付</div>
    </div>
  </div>
</template>
<script>
import {Tab, TabItem} from "vux";
import {getPayListNew, payCreate, queryOrderStatus, getOutpatientUnPayAmount} from "@/api/api";
import {getWxUserinfoCookies} from "@/api/auth";
import Vue from "vue";

export default {
  components: {
    Tab,
    TabItem,
  },
  data() {
    return {
      isPayClick: false,
      tabItemShow: '0',
      info: {},
      unpayList: [],
      payList: [],
      payInfo: {
        unPay: 0,

      },
      count: 0
    };
  },
  created() {
    if (window.localStorage.getItem("outpatientPaymentShow")) {
      this.tabItemShow = window.localStorage.getItem("outpatientPaymentShow")
    }
    this.info = this.$route.query
    this.getPayListNew();
  },
  methods: {
    getPayListNew() {
      getPayListNew({
        hosId: this.info.hosId || "21010005",
        idcardNo: this.info.idcardNo,
        patientName: this.info.patientName,
        hospPatientId: this.info.hospPatientId
      }).then((res) => {
        if (res.code == 200) {
          this.payInfo = res.data;
          var resData = res.data.payList || [], list1 = [], list2 = []
          resData.forEach(element => {
            if (element.orderStatus == 0) {
              list1.push(element)
            } else {
              list2.push(element)
            }
          });
          this.unpayList = list1
          this.payList = list2

        }
      });
    },
    getLocalOpenId() {
      //获取openId
      try {
        var user = JSON.parse(getWxUserinfoCookies());
        if (user && user.openid.trim().length > 0) {
          return user.openid;
        } else {
          console.log("getWxUserinfoCookies 未获取到微信openid");
          var openId = window.localStorage.getItem("openId");
          return openId;
        }
      } catch (err) {
        console.log(err)
        var openId = window.localStorage.getItem("openId");
        return openId;
      }
    },
    getOutpatientUnPayAmount(orderId) {
      getOutpatientUnPayAmount({
        clinicSerialNo: this.info.idcardNo
      }).then(res => {
        if (res.code == 200) {
          var amount = parseFloat(res.data.amount)
          var totalAmount = parseFloat(this.payInfo.totalAmount / 100)
          if (amount - totalAmount == 0) {
            this.payCreate(orderId);
          } else {
            // alert("医嘱有变，请重新支付")
            this.$vux.alert.show({
              title: '提示',
              content: '医嘱有变，请重新支付',
            })
            this.getPayListNew()
          }
        }
      })
    },
    goPay(orderId) {
      if (this.isPayClick) {
        console.log("请勿重复支付!")
        return;
      }
      this.isPayClick = true;
      setTimeout(function () {
        this.isPayClick = false;
      }, 3000);
      Vue.$vux.loading.show({text: '请求支付信息...'});
      // 获取微信配置
      this.getOutpatientUnPayAmount(orderId)

    },
    payCreate(orderId) {
      var openId = this.getLocalOpenId();
      if (openId == '' || openId.length < 20) {
        //未获取到openId  先去首页获取登录
        this.$router.push({path: "/"});
        return;
      }
      payCreate({
        orderType: "2",
        orderId,
        openId: openId,
      }).then((res) => {
        this.isPayClick = false;
        if (res.code == 200) {
          // 调起微信支付
          let resData = res.data
          this.wxPay(resData, orderId);
        } else {

          if (res.code == 1355) {
            this.$router.push({
              name: "outpatient_payment",
            });
          } else {
            //报错跳转到首页
            alert(res.message);
            this.$router.push({path: "/"});
          }
        }
      });
    },
    // 发起微信支付
    wxPay(data, orderId) {
      Vue.$vux.loading.hide();//隐藏loading
      const that = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: data.appId, //公众号名称，由商户传入
          timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式：
          paySign: data.paySign, //微信签名
        },
        function (response) {
          //TODO 应该再进行一次查单验证来保证支付成功
          if (response.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回get_brand_wcpay_request:ok，但并不保证它绝对可靠。
            that.$vux.loading.show()
            that.queryOrderStatusFun(orderId)
          } else {
            that.$vux.toast.show("支付失败")

          }
        }
      );
    },
    queryOrderStatusFun(orderId) {
      queryOrderStatus({
        orderId, //订单号
        "orderType": "2" //1:挂号 2:缴费
      }).then(res => {
        this.count++
        // 轮询6次
        if (this.count < 6) {
          if (res.code == 200) {
            this.$vux.loading.hide()
            this.getPayListNew()
            this.$vux.alert.show({
              title: '提示',
              content: '门诊缴费成功',
            })
            // alert("门诊缴费成功")
            return
          } else if (res.code == 400) {
            if (res.message == 'NOTIFY_HIS_ERROR') {

              this.$vux.loading.hide()
              this.getPayListNew()
              this.$vux.alert.show({
                title: '提示',
                content: '门诊缴费失败，请联系我院进行退费',
              })

              // alert("门诊缴费失败，请联系我院进行退费")
              this.count = 0
              return
            } else {
              setTimeout(() => {
                this.queryOrderStatusFun(orderId)
              }, 2000)
            }

          } else {
            this.$vux.loading.hide()
            this.getPayListNew()
            this.$vux.alert.show({
              title: '提示',
              content: '门诊缴费失败，请联系我院进行退费',
            })
            // alert("门诊缴费失败")
            this.count = 0
            return
          }
        } else {
          this.$vux.loading.hide()
          // alert("门诊缴费失败，请联系我院进行退费")
          this.getPayListNew()
          this.$vux.alert.show({
            title: '提示',
            content: '门诊缴费失败，请联系我院进行退费',
          })

          this.count = 0
          return
        }

      })
    },

    // 跳转缴费详情
    godetail(item) {
      window.localStorage.setItem("outpatientPaymentShow", this.tabItemShow)
      switch (item.orderStatus) {
        // 待缴费
        case "0":
          this.$router.push({
            path: "/outpatient_payment_unpaid",
            query: {
              hospSequence: item.hospSequence,
              clinicCode: this.payInfo.idcardNo
            },
          });
          break;
        // 已缴费
        case "1":
          this.$router.push({
            path: "/outpatient_payment_paid",
            query: {
              hospSequence: item.hospSequence,
              clinicCode: this.payInfo.idcardNo
            },
          });
          break;
        // 已失效 已退款
        case "2":
          //   this.$router.push({
          //     path: "/outpatient_payment_lost",
          //     query: {
          //       hospSequence: item.hospSequence,
          //     },
          //   });
          break;
        default:
          break;
      }
    },
    tabItemClick(e) {
      this.tabItemShow = e

    },
  },
  filters: {
    changAmout(amout) {
      var amoutNew = (parseFloat(amout) / 100).toFixed(2);
      return amoutNew;
    },
  },
};
</script>
<style scoped>
.billBox {
  width: 100%;
  height: calc(100vh - 2.75rem);
  overflow-y: scroll;
  background: #f4f8fc;
  /* padding: 1rem 0; */
  position: relative;
}

.bill_box {
  margin: 0.75rem 1rem;
  padding: 0px 1rem;
  width: calc(100% - 4rem);
  /* height: 10.5rem; */
  padding-bottom: 0.75rem;
  background-color: #ffffff;
  box-shadow: 0px 0px 10px 0px rgba(174, 206, 254, 0.24);
  border-radius: 0.375rem;
  position: relative;
}

.bill_box .bill_box_1 {
  height: 2.8125rem;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e7ecf5;
}

.bill_box_1_status {
  position: absolute;
  right: 10px;
  top: 10px;
  width: 4.5rem;
  height: 3.5rem;

}

.bill_box .bill_box_2 {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.bill_box .bill_box_2 .left {
  width: calc(100%);
  /* height: 7.5rem; */
  display: flex;
  /* align-items: center; */
  justify-content: space-around;
  flex-flow: column;
}

.bill_box .bill_box_2 .left > div {
  line-height: 25px;
}


.bill_box .bill_box_2 .left .gery {
  font-size: 0.75rem;
  color: #a4adbe;
}

.bill_box .bill_box_2 .paybtn {
  width: 3.4375rem;
  height: 1.875rem;
  border: 1px solid #448eff;
  border-radius: 3px;
  color: #448eff;
  text-align: center;
  line-height: 1.875rem;
}

.payBottom {
  width: 100%;
  height: 3.4375rem;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  bottom: 0;
}

.payBottom_1 {
}

.payBottom_1 span {
  color: #f62d40;
}

.payBottom_2 {
  height: 3.4375rem;
  width: 8.75rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(90deg, #448eff 0%, #66a3ff 100%);
  font-size: 18px;
  font-family: PingFang SC;
  font-weight: bold;
  color: #ffffff;
}

.bill_box_img {
  position: absolute;
  top: 37%;
  right: 1rem;
  color: #A4ADBE;
}

.bill_box_img img {
  width: 0.5rem;
  height: 0.8125rem;
  margin-left: 0.625rem;

}

.noresult {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column;
  height: 31.25rem;
}

.noresult img {
  display: block;
  width: 12.5rem;
  height: 9.75rem;
}
</style>
<style>
.weui-dialog__btn_primary {
  color: #448eff;
}
</style>
